/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package BrowseGoods;

import dataclass.*;
import java.lang.*;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.List;
import java.util.*;
import dataclass.Storage;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author 周文华
 */
public class ShoppingCartJFrame extends javax.swing.JFrame {

    /**
     * Creates new form ShoppingCartJFrame
     */
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        totalMoneyJLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        ensureJButton = new javax.swing.JButton();
        modifyJLabel = new javax.swing.JLabel();
        countJTextField = new javax.swing.JTextField();
        deleteJButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        showCartTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("我的购物车");

        jLabel1.setText("总计：");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(totalMoneyJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 415, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(totalMoneyJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap(43, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(23, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        ensureJButton.setText("确定");
        ensureJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ensureJButtonActionPerformed(evt);
            }
        });

        modifyJLabel.setText("修改：");

        countJTextField.setText("quantity");
        countJTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                countJTextFieldFocusLost(evt);
            }
        });
        countJTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                countJTextFieldActionPerformed(evt);
            }
        });

        deleteJButton.setText("删除");
        deleteJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteJButtonActionPerformed(evt);
            }
        });

        jButton1.setText("清空购物车");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(modifyJLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                        .addComponent(countJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ensureJButton)
                            .addComponent(deleteJButton)
                            .addComponent(jButton1))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(modifyJLabel)
                    .addComponent(countJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ensureJButton)
                .addGap(56, 56, 56)
                .addComponent(deleteJButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        showCartTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "商品编号", "商品名称", "商品单价", "商品种类", "商品数量", "商品小计"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(showCartTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 437, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void deleteJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteJButtonActionPerformed
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) showCartTable1.getModel();
        int rowIndex = showCartTable1.getSelectedRow();

        if (rowIndex != -1) {
            String str = (String) model.getValueAt(rowIndex, 0);
            int id = Integer.parseInt(str);
            boolean result = BrowseJFrame.cart.deleteGoods(id);
            if (result) {
                model.removeRow(rowIndex);
                double allMoney=BrowseJFrame.cart.allTotalMoney();
         String a=String.format("%.2f", allMoney);
             totalMoneyJLabel.setText(a);
                JOptionPane.showMessageDialog(null, "删除成功");

            }
            if (!result) {
                JOptionPane.showMessageDialog(null, "删除失败");
            }

        } else {
            JOptionPane.showMessageDialog(null, "未选择");
        }
    }//GEN-LAST:event_deleteJButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        boolean result = BrowseJFrame.cart.clearShoppingCart();
        DefaultTableModel model = (DefaultTableModel) showCartTable1.getModel();
        if (result) {
            int rows = showCartTable1.getRowCount();
            double allMoney=0.0;
            while (rows >= 1) {
                model.removeRow(--rows);
               allMoney=BrowseJFrame.cart.allTotalMoney();
        
            }
             String a=String.format("%.2f", allMoney);
             totalMoneyJLabel.setText(a);
            JOptionPane.showMessageDialog(null, "购物车已清空");
        } else {

            JOptionPane.showMessageDialog(null, "清空失败");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void ensureJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ensureJButtonActionPerformed
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) showCartTable1.getModel();
        String content = countJTextField.getText();
        int count = Integer.parseInt(content);

        int rowIndex = showCartTable1.getSelectedRow();
        if(rowIndex!=-1){
        String str = (String) model.getValueAt(rowIndex, 0);
        int id = Integer.parseInt(str);

        int result = BrowseJFrame.cart.modifyGoods(id, count);

        if (result == 1) {
            String price1 = (String) model.getValueAt(rowIndex, 2);
            double price = Double.parseDouble(price1);
            double totalMoney = price * count;
            model.setValueAt(count, rowIndex, 4);
            model.setValueAt(totalMoney, rowIndex, 5);
          double allMoney=BrowseJFrame.cart.allTotalMoney();
         String a=String.format("%.2f", allMoney);
             totalMoneyJLabel.setText(a);
            JOptionPane.showMessageDialog(null, "修改成功");
        }
        if (result == 0) {
            JOptionPane.showMessageDialog(null, "库存不足");
        }}else
            JOptionPane.showMessageDialog(null,"未选择");

    }//GEN-LAST:event_ensureJButtonActionPerformed

    private void countJTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_countJTextFieldFocusLost
        // TODO add your handling code here:
        String content = countJTextField.getText();
        try {
            int count = Integer.parseInt(content);
        } catch (java.lang.NumberFormatException ex) {
            JOptionPane.showMessageDialog(null, "数量为整数");
        }
    }//GEN-LAST:event_countJTextFieldFocusLost

    private void countJTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_countJTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_countJTextFieldActionPerformed

    public ShoppingCartJFrame() {
        initComponents();
        showCart();

    }

    public void showCart() {

        DefaultTableModel model = (DefaultTableModel) showCartTable1.getModel();
        Collection<GoodsItem> goodsItems = BrowseJFrame.cart.getGoodsList().values();
        Iterator<GoodsItem> iterator = goodsItems.iterator();
        String[] strs = new String[6];

        while (iterator.hasNext()) {
            GoodsItem goodsItem = iterator.next();
            Goods goods = goodsItem.getGood();
            Integer id = goods.getGoodId();
            String name = goods.getGoodName();
            double price = goods.getGoodprice();
            String category = goods.getGoodCategory();
            Integer count = goodsItem.getCount();
            double totalMoney = goodsItem.totalMoney();
            String totalMoney1=String.format("%.2f", totalMoney);

            strs[0] = "" + id;
            strs[1] = "" + name;
            strs[2] = "" + price;
            strs[3] = "" + category;
            strs[4] = "" + count;
            strs[5] = "" + totalMoney1;
            // System.out.println(Arrays.toString(strs));
            model.addRow(strs);

        }
         double allMoney=BrowseJFrame.cart.allTotalMoney();
         String a=String.format("%.2f", allMoney);
             totalMoneyJLabel.setText(a);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ShoppingCartJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ShoppingCartJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ShoppingCartJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ShoppingCartJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ShoppingCartJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField countJTextField;
    private javax.swing.JButton deleteJButton;
    private javax.swing.JButton ensureJButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel modifyJLabel;
    private javax.swing.JTable showCartTable1;
    private javax.swing.JLabel totalMoneyJLabel;
    // End of variables declaration//GEN-END:variables
}
